from django.shortcuts import render

# Create your views here.
from rest_framework.views import APIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework import status
from django.utils import timezone as datetime
from django.conf import settings
import random
from alipay import AliPay
from article.models import Article
from .models import Reward

class ALIPayAPIView(APIView):

    permission_classses = [IsAuthenticated]

    def post(self,request):
        #生成创建打赏相关对象
        money = request.data.get("money")
        article_id = request.data.get("article_id")
        try:
            article = Article.objects.get(pk=article_id, is_show=True, is_deleted=False, is_public = True)
        except Article.DoesNotExist:
            return Response({"detail":"文章不存在"},status=status.HTTP_400_BAD_REQUEST)
        user = request.user
        out_trade_no =datetime.now().strftime("%Y%m%d%H%M%S") + ("%06d" % user.id) + ("%06d" % random.randint(1, 999999))
        reward = Reward.objects.create(
            user = user,
            money=float(money),
            article = article,
            reward_type=1,
            message = request.data.get("message"),
            out_trade_no=out_trade_no
        )
        #支付宝接口相关配置
        app_private_key_string = open(settings.ALIPAY.get("app_private_key_path")).read()
        alipay_public_key_string= open(settings.ALIPAY.get("alipay_public_key_path")).read()
        alipay = AliPay(
            appid=settings.ALIPAY.get("appid"),  # appid
            app_notify_url=settings.ALIPAY.get("app_notify_url"),  # 默认回调url
            app_private_key_string=app_private_key_string,
            alipay_public_key_string=alipay_public_key_string,
            sign_type=settings.ALIPAY.get("sign_type"),
            debug=settings.ALIPAY.get("debug")
        )
        order_string = alipay.api_alipay_trade_page_pay(
            out_trade_no=out_trade_no,  # 订单号
            total_amount=float(money),  # 订单金额
            subject="打赏文章《%s》" % article.title,  # 订单标题
            return_url=settings.ALIPAY.get("return_url"),  # 订单的同步回调地址[js跳转]
            notify_url=settings.ALIPAY.get("notify_url")  # 订单的异步回调地址[由支付宝主动发起请求到api服务端的地址]
        )
        url = settings.ALIPAY.get("gateway_url") + order_string

        return Response(url)

from users.models import User
class AlipayResultAPIView(APIView):
    '''
    同步结果：将参数附带在url上跳转到制定客户端页面
    异步结果：会以http-post方式把支付结果作为请求发送过来，服务器必须在公网上
    '''

    def get(self,request):

        # for rest_framework users
        data = request.query_params.dict()

        signature = data.pop("sign")

        app_private_key_string = open(settings.ALIPAY.get("app_private_key_path")).read()
        alipay_public_key_string = open(settings.ALIPAY.get("alipay_public_key_path")).read()
        alipay = AliPay(
            appid=settings.ALIPAY.get("appid"),  # appid
            app_notify_url=settings.ALIPAY.get("app_notify_url"),  # 默认回调url
            app_private_key_string=app_private_key_string,
            alipay_public_key_string=alipay_public_key_string,
            sign_type=settings.ALIPAY.get("sign_type"),
            debug=settings.ALIPAY.get("debug")
        )
        # verification
        success = alipay.verify(data, signature)
        if success :
            out_trade_no = data.get("out_trade_no")
            try:
                reward = Reward.objects.get(out_trade_no=out_trade_no,status=False)
            except Reward.DoesNotExist:
                return Response("订单已经完成或者支付失败")
            reward.status = True
            reward.trade_no = data.get("trade_no")
            reward.article.user.money+=reward.money
            reward.article.user.save()
            reward.save()
            return Response({"detail":"支付成功"},{"article_id": reward.article.id})
        return Response({"detail":"打赏失败，请联系管理员"})